package com.gzx.risk.core.apis.result.tanzhi;

import com.alibaba.fastjson2.JSONObject;
import com.gzx.risk.core.apis.result.RiskResult;
import com.gzx.risk.core.utils.ParseVariableUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.util.HashMap;
import java.util.Map;

@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class TanzhiGlobalRisk extends RiskResult {
	private String code;
	private String msg;
	private Map<String, Object> data;
    private Map<String, Object> parsedVariables;

    /**
     * 检查接口调用是否成功
     * @return 是否成功
     */
    public boolean isSuccess() {
        return "0000".equals(code);
    }

    public String getValue(String key) {
        if (data != null && data.containsKey(key)) {
            return data.get(key).toString();
        } else {
            return "";
        }
    }

    public Double getScore(String key) {
        String value = getValue(key).trim();
        if (value.length() > 0) {
            return Double.valueOf(value);
        } else {
            return -1.0;
        }
    }

    public Integer getParsedValue(String key) {
        Map<String, Object> parsed = getParsedVariables();
        Object val = parsed.get(key);
        if (val instanceof Integer) {
            return (Integer) val;
        } else if (val != null) {
            try {
                return Integer.parseInt(val.toString());
            } catch (NumberFormatException e) {
                return -1;
            }
        }
        return -1;
    }

    public Map<String, Object> getParsedVariables() {
        if (parsedVariables != null) {
            return parsedVariables;
        }
        if (data == null || data.isEmpty()) {
            parsedVariables = new HashMap<>();
        } else {
            JSONObject jsonData = new JSONObject();
            jsonData.putAll(data);
            parsedVariables = ParseVariableUtil.parseVariable(jsonData);
        }
        return parsedVariables;
    }
}
